<template>
  <div class="container">
    <!-- 成员信息 -->
    <div class="content">
      <div class="searchhead">
        <el-select
          v-model="groupQueryInfo.grade"
          placeholder="年级筛选"
          @change="getGroupMembers"
        >
          <el-option
            v-for="item in gradeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>

        <el-select
          @change="getGroupMembers"
          v-model="groupQueryInfo.isLeader"
          placeholder="是否仅看组长"
        >
          <el-option
            v-for="item in isLeaderOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>

        <el-input
          placeholder="搜索学号、姓名"
          v-model="groupQueryInfo.keyword"
          class="input-with-select"
          @keyup.enter.native="getGroupMembers()"
        >
          <el-button
            @click="getGroupMembers"
            slot="append"
            icon="el-icon-search"
          ></el-button>
        </el-input>

        <el-button type="info" plain @click="beginDistribution">
          <i class="el-icon-guide"></i>
          <span v-show="!distributionShow"> 小组分流</span>
          <span v-show="distributionShow"> 取消分流</span>
        </el-button>

        <el-button
          class="loadButton left"
          type="success"
          @click="downloadTemplate"
        >
          <i class="el-icon-download"></i>
          下载模板
        </el-button>

        <el-upload
          action="uploadUrl"
          accept=".xls,.xlsx"
          :headers="token"
          :file-list="fileList"
          :limit="1"
          :on-change="handleFileChange"
          :show-file-list="false"
          :on-success="handleSuccess"
          :on-error="handleError"
          :auto-upload="true"
          :http-request="uploadTemplate"
        >
          <el-button class="loadButton right" type="primary">
            <i class="el-icon-upload2"></i> 上传名单
          </el-button>
        </el-upload>
      </div>

      <div v-show="distributionShow" class="distribution">
        <label>已选择 {{ distributeMembers.length }} 项，</label>
        <label>分流至：</label>
        <el-select
          v-model="distributeTo"
          placeholder="选择分流小组"
          size="mini"
        >
          <el-option
            v-for="item in distributeGroups"
            :key="item.groupId"
            :label="item.groupName"
            :value="item.groupId"
          >
          </el-option>
        </el-select>
        <el-button
          @click="distributeGroupMember"
          class="distriButton"
          type="info"
          plain
          size="mini"
          >确认分流</el-button
        >
      </div>

      <!-- 成员表格渲染 -->
      <el-table
        :data="members"
        v-loading="isLoading.status"
        border
        stripe
        style="width: 100%"
        @selection-change="handleTableSelectionChange"
      >
        <el-table-column v-if="distributionShow" width="50" type="selection">
        </el-table-column>
        <!-- <el-table-column
          v-if="distributionShow==false"
          type="index"
          label="#"
          align="center"
        ></el-table-column> -->
        <el-table-column
          prop="realName"
          label="姓名"
          min-width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="grade"
          label="年级"
          min-width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="studentId"
          label="学号"
          min-width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="groupName"
          label="所属组"
          min-width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="identity"
          label="职位"
          min-width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="qq"
          label="QQ"
          min-width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          min-width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="180"
          align="center"
        ></el-table-column>
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template slot-scope="scope">
            <!--查看按钮-->
            <el-tooltip
              effect="dark"
              content="查看/编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-s-data"
                size="mini"
                plain
                @click="editMember(scope.row)"
              >
              </el-button>
            </el-tooltip>
            <!--删除按钮-->
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                @click="removeMember(scope.row.userId)"
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
              >
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="groupQueryInfo.pageNum"
        :page-sizes="[2, 5, 10, 30, 50, 100]"
        :page-size="groupQueryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalPage"
      >
      </el-pagination>
    </div>

    <!-- 个人信息的Dialog -->
    <el-dialog
      :visible.sync="personDialogShow"
      title="成员信息"
      width="40%"
      :modal-append-to-body="false"
      :close-on-click-modal.sync="personDialogReadOnly"
      :before-close="handleDialogClose"
    >
      <el-form ref="person" :model="person" label-width="85px">
        <el-form-item label="姓名" prop="realName">
          <el-input :disabled="personDialogReadOnly" v-model="person.realName">
          </el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="person.gender" :disabled="personDialogReadOnly">
            <el-option
              v-for="item in genderType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="年级" prop="grade">
          <el-input :disabled="personDialogReadOnly" v-model="person.grade">
          </el-input>
        </el-form-item>
        <el-form-item label="学号" prop="realName">
          <el-input :disabled="personDialogReadOnly" v-model="person.studentId">
          </el-input>
        </el-form-item>
        <el-form-item label="所属组" prop="groupName">
          <el-input disabled v-model="person.groupName"> </el-input>
        </el-form-item>
        <el-form-item label="职位" prop="identity">
          <el-input disabled v-model="person.identity"> </el-input>
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input :disabled="personDialogReadOnly" v-model="person.qq">
          </el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input :disabled="personDialogReadOnly" v-model="person.mobile">
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input :disabled="personDialogReadOnly" v-model="person.email">
          </el-input>
        </el-form-item>
        <div class="submitForm">
          <el-button type="info" plain @click="handleEditButton"
            ><span v-show="personDialogReadOnly"> 编辑</span>
            <span v-show="!personDialogReadOnly">取消</span></el-button
          >
          <el-button type="primary" plain @click="submitEditPerson('person')"
            >提交</el-button
          >
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import ParamUtil from "../utils/paramsConvert";
export default {
  name: "structure-card",
  components: {},
  props: {
    groupId: Number,
  },

  data() {
    return {
      person: {
        email: "",
        gender: "",
        groupName: "",
        identity: "",
        mobile: "",
        qq: "",
        realName: "",
        studentId: "",
        userId: "",
      },
      personDialogShow: false,
      personDialogReadOnly: true,
      distributionShow: false,
      distributeTo: "",
      distributeGroups: {},
      distributeMembers: [],
      isLoading: {
        status: false,
      },
      groupQueryInfo: {
        keyword: "",
        grade: "",
        isLeader: 0,
        groupId: "",
        pageNum: 1,
        pageSize: 10,
      },
      members: [],
      totalPage: 0,
      file: "",
      fileList: [],
      selectGroupId: "",
      groupTypeOptions: [],
      gradeOptions: [],
      isLeaderOption: [
        {
          value: 1,
          label: "仅看组长",
        },
        {
          value: 0,
          label: "全部学员",
        },
      ],
      uploadUrl: `${this.HOST}/admin/api/uploadUserModel`,
      token: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      genderType: [
        {
          value: 1,
          label: "男",
        },
        {
          value: 0,
          label: "女",
        },
      ],
    };
  },

  created() {
    // Init Grade
    let year = new Date().getFullYear();
    let grade = [];
    while (year >= 2019) {
      let obj = {
        value: year,
        label: year + "级",
      };
      grade.push(obj);
      year--;
    }
    this.gradeOptions = grade;
  },

  mounted() {},

  methods: {
    updateGroupId(groupId) {
      this.groupQueryInfo.groupId = groupId;
      this.getGroupMembers();
      this.getCurrentChildGroup(groupId);
    },
    /**
     * 下载成员模板
     */
    async downloadTemplate() {
      const res = await this.$axios.get(
        `${this.HOST}/admin/api/downloadUserModel`,
        { responseType: "blob" }
      );
      let data = res.data;
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      a.setAttribute("download", "IT培优学员信息统计模板.xls");
      document.body.appendChild(a);
      a.click(); //执行下载
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    },
    /**
     * 上传名单
     */
    async uploadTemplate() {
      let formData = new FormData();
      formData.append("file", this.file.raw);
      const res = await this.$axios.post(
        `${this.HOST}/admin/api/uploadUserModel`,
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
          responseType: "blob",
        }
      );
      // console.log(res);
      let data = res.data;
      this.getGroupMembers();
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      a.setAttribute("download", "录入失败的错误信息.xls");
      document.body.appendChild(a);
      a.click(); //执行下载
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    },
    /**
     * 处理上传文件变化
     */
    handleFileChange(file) {
      this.file = file;
      console.log("file", this.file);
    },
    handleSuccess() {
      this.file = "";
      this.fileList = [];
      this.$message.success("上传成功！");
    },
    handleError(err) {
      console.log("err", err);
      this.file = "";
      this.fileList = [];
      this.$message.error("上传失败，请重试！");
    },
    /**
     * 获取组成员信息
     */
    async getGroupMembers() {
      this.isLoading.status = true;
      let params = this.groupQueryInfo;
      const res = await this.$axios.post(
        `${this.HOST}/group/api/groupMember`,
        params
      );
      if (res.data.meta.code == 200) {
        let data = res.data.data;
        this.totalPage = data.members.total;
        this.members = data.members.list;
        console.log("成员信息获取成功！", this.members);
      }
      this.isLoading.status = false;
    },
    /**
     * 监听pagesiez的改变
     * newSiez 当前的每一页的size
     */
    handleSizeChange(newSize) {
      this.groupQueryInfo.pageSize = newSize;
      this.getGroupMembers();
    },
    /**
     * 监听页码值变化
     * newPage 当前页
     */
    handleCurrentChange(newPage) {
      this.groupQueryInfo.pageNum = newPage;
      this.getGroupMembers();
    },
    editMember(person) {
      // console.log("per", person);
      this.person = Object.assign({}, person); // 拷贝对象，防止引用
      console.log("edit", this.person);
      this.personDialogShow = true;
    },
    removeMember(userId) {
      this.$confirm("此操作将永久删除该学员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        // console.log("delete", userId);
        const res = await this.$axios.get(
          `${this.HOST}/group/api/deleteUser/` + userId
        );
        if (res.data.meta.code == 200) {
          this.$message.success("删除成功！");
          this.getGroupMembers();
        }
      });
    },
    async submitEditPerson() {
      // console.log("pe",this.person);
      let params = {
        userId: this.person.userId,
        realName: this.person.realName,
        email: this.person.email,
        gender: this.person.gender,
        grade: this.person.grade,
        mobile: this.person.mobile,
        studentId: this.person.studentId,
        qq: this.person.qq,
      };
      const res = await this.$axios.post(
        `${this.HOST}/group/api/updateUser`,
        params
      );
      if (res.data.meta.code == 200) {
        this.$message.success("修改成功！");
        this.personDialogShow = false;
        this.getGroupMembers();
      }
    },
    changeHandler() {
      // console.log(this.person);
    },
    /**
     * 查看成员信息框的关闭
     */
    handleDialogClose(done) {
      this.personDialogReadOnly = true;
      return done();
    },
    /**
     * 处理信息框的 编辑/取消 的切换
     */
    handleEditButton() {
      this.personDialogReadOnly = !this.personDialogReadOnly;
      if (this.personDialogReadOnly) {
        this.personDialogShow = false;
        this.personDialogReadOnly = true;
      }
    },
    /**
     * 点击《分流》按钮，开始进行分流操作
     */
    beginDistribution() {
      // 展示分流栏，再次点击关闭
      this.distributionShow = !this.distributionShow;
    },
    /**
     * 处理多选变化
     */
    handleTableSelectionChange(val) {
      this.distributeMembers = val;
    },
    /**
     * 获取当前组下所有小组信息
     */
    async getCurrentChildGroup(groupId) {
      const res = await this.$axios.get(
        `${this.HOST}/group/api/lastGroups/` + groupId
      );
      if (res.data.meta.code == 200) {
        this.distributeGroups = res.data.data.groups;
        console.log("获取当前组下小组信息成功！", this.distributeGroups);
      }
    },
    /**
     * 处理分流操作
     */
    async distributeGroupMember() {
      if (this.distributeMembers == "") {
        this.$message.warning("请至少选择一个对象！");
        return;
      } else if (this.distributeTo == "") {
        this.$message.warning("请选择分流至的小组！");
        return;
      }
      // 提取成员id
      let userIds = [];
      this.distributeMembers.forEach((ele) => {
        userIds.push(ele.userId);
      });
      let params = {
        userIds: userIds,
        groupId: this.distributeTo,
      };
      // axios
      const res = await this.$axios.post(
        `${this.HOST}/group/api/diversion`,
        params
      );
      if (res.data.meta.code == 200) {
        this.$message.success("处理成功！");
        this.distributionShow = false;
        this.getGroupMembers();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.header {
  color: white;
  font-size: 28px;
  font-weight: bold;
  width: 100%;
  text-align: center;
  height: 50px;
  margin-bottom: 10px;
}

.content {
  width: 75%;
  min-width: 800px;
  margin: auto;
  border-radius: 5px;
  padding: 20px;
  background-color: white;
  padding-right: 40px;
  font-weight: normal;
  padding-left: 40px;
  color: gray;
  margin-bottom: 20px;
}

.searchhead {
  min-width: 800px;
  height: 40px;
  display: flex;

  .input-with-select {
    width: 200px;
    border-radius: 5px;
    margin-right: 10px;
    // border: 1px gray solid;

    // /deep/ .el-input__inner {
    // border-radius: 5px;
    // border: 1px gray solid;

    // &::placeholder {
    // color: rgba(114, 112, 112, 0.527);
    // }
    // }
  }

  .loadButton {
    margin-left: 20px;
  }
  .left {
    margin-left: auto;
  }

  /deep/.el-select {
    width: 150px;
    margin-right: 10px;
  }
}

.distribution {
  display: flex;
  margin-top: 10px;
  line-height: 28px;

  /deep/ .el-input--mini {
    width: 150px !important;
  }

  .distriButton {
    margin-left: 10px;
  }
}

.submitForm {
  display: flex;
  justify-content: center;
}

.checkbox {
  margin-left: 10px;
  font-size: 26px;
  color: gray;
}
</style>
